//package com.erp.freight.controller;
//
//import cn.hutool.core.bean.BeanUtil;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.erp.freight.domain.EjfLogisticsProductInfo;
//import com.erp.freight.domain.ejf.EJFCreateOrder;
//import com.erp.freight.domain.ejf.EJFParcelInfo;
//import com.erp.freight.domain.ejf.EJFProductList;
//import com.erp.freight.domain.ejf.EJFReceiverInfo;
//import com.erp.freight.domain.param.OrderParam;
//import com.erp.freight.mapper.EjfLogisticsProductInfoMapper;
//import com.fpx.api.utils.MD5Util;
//import com.ruoyi.common.core.domain.R;
//import com.ruoyi.common.core.utils.JsonUtils;
//import com.ruoyi.common.redis.utils.RedisUtils;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.HttpEntity;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.util.EntityUtils;
//import org.springframework.web.bind.annotation.*;
//
//import java.io.IOException;
//import java.nio.charset.StandardCharsets;
//import java.time.Duration;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//@RequiredArgsConstructor
//@RestController
//@RequestMapping("/purchase/ejfLogistics")
//@Slf4j
//public class EJFLogistics {
//
//    private static final String userId = "100000";
//    private static final String format = "json";
//    private static final String apiToken = "D6140AA383FD8515B09028C586493DDB";
//    private static final String version = "V1.0";
//    private static final String testAddr = "https://ejf-fat.yw56.com.cn";
//    private static final String formalAddr = "https://open.yw56.com.cn";
//    private static final String apiOrder = "/api/order";
//
//    private final EjfLogisticsProductInfoMapper productInfoMapper;
//    private final AeStoreOrderReceiptAddressMapper addressMapper;
//    private final ErpCollectProductExpandMapper collectProductExpandMapper;
//    private final IErpSellerChildOrderService sellerChildOrderService;
//    private final ErpCollectProductSkuMapper collectProductSkuMapper;
//    private final IErpCollectProductService collectProductService;
//
//
//    /**
//     * 创建运单
//     */
//    @PostMapping("/createOrder")
//    public String createOrder(@RequestBody OrderParam orderParam) {
//        String method = "express.order.create";
//        Map<String, Object> paramMap = new HashMap<>();
//        Long orderId = orderParam.getOrderId();
//        EJFCreateOrder createOrder = new EJFCreateOrder();
//        createOrder.setChannelId("128");
//        createOrder.setOrderSource("庞博erp");
//        createOrder.setOrderNumber(orderId.toString());
//        createOrder.setCompanyCode("");
//        // 根据订单查询收件人信息
//        EJFReceiverInfo receiverInfo = new EJFReceiverInfo();
//        AeStoreOrderReceiptAddress address = addressMapper.selectOne(new LambdaQueryWrapper<AeStoreOrderReceiptAddress>().eq(AeStoreOrderReceiptAddress::getOrderId, orderId));
//        receiverInfo.setPhone(address.getPhoneNumber());
//        receiverInfo.setCountry(address.getPhoneNumber());
//        receiverInfo.setName(address.getContactPerson());
//        receiverInfo.setCity(address.getCity());
//        receiverInfo.setState(address.getProvince());
//        receiverInfo.setZipCode(address.getZip());
//        String house = address.getAddress() != null? address.getAddress() : "" + address.getAddress2();
//        if (house.length() < 50) { // 门牌号太长,不传了
//            receiverInfo.setHouseNumber(house);
//        }
//        createOrder.setReceiverInfo(receiverInfo);
//
//        // 根据orderId获取商品信息
//        List<ErpSellerChildOrder> childOrderList = sellerChildOrderService.getChildOrderByOrderId(orderId);
//
//        EJFParcelInfo parcelInfo = new EJFParcelInfo();// 包裹信息
//        // 商品信息
//        List<EJFProductList> productLists = new ArrayList<>();
//        EJFProductList productList = new EJFProductList();
//        double totalPrice = 0.00; // 总价值
//        int totalCount = 0; // 总数量
//        String currency = null;
//        for (ErpSellerChildOrder childOrder : childOrderList) {
//
//            String productPrice = childOrder.getProductPrice(); // 单价
//            Double price = new Double(productPrice);
//            int productCount = childOrder.getProductCount().intValue(); // 数量
//            String skuCode = childOrder.getSkuCode();
//            ErpCollectProductSku skuInfo = collectProductSkuMapper.selectOne(
//                    new LambdaQueryWrapper<ErpCollectProductSku>()
//                            .eq(ErpCollectProductSku::getSkuCode, skuCode)
//                            .eq(ErpCollectProductSku::getDelFlag, "0")
//            );
//            Long collectProductId = skuInfo.getCollectProductId();
//            String categoryEn = collectProductService.getCategoryEn(collectProductId);
//            String categoryCN = collectProductService.getCategoryCN(collectProductId);
//            productList.setGoodsNameEn(categoryEn);
//            productList.setGoodsNameCh(categoryCN);
//            productList.setPrice(price);
//            productList.setQuantity(productCount);
//            productList.setWeight(skuInfo.getSkuWeight());
//            productLists.add(productList);
//            totalPrice += price;
//            totalCount += productCount;
//            currency = childOrder.getProductCurrencyCode();
//            productList = new EJFProductList();
//        }
//        // 包裹信息
//        parcelInfo.setProductList(productLists);
//        parcelInfo.setTotalPrice(totalPrice);
//        parcelInfo.setTotalQuantity(totalCount);
//        parcelInfo.setCurrency(currency);
//
//
//        return null;
//    }
//
//    /**
//     * 打印国际物流面单
//     */
//    @GetMapping("/getLabel")
//    public R<Object> getLabel(String waybillNumber) {
//        String method = "express.order.label.get";
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("waybillNumber", waybillNumber);
//        String string = JsonUtils.toJsonString(paramMap);
//        String returnBody = getReturnBody(string, method, apiOrder);
//        JSONObject jsonObject = JSONObject.parseObject(returnBody);
//        Boolean success = jsonObject.getBoolean("success");
//        if (success) {
//            return R.ok(jsonObject.getJSONObject("data").getString("base64String"));
//        }else {
//            return R.fail(jsonObject.getString("message"));
//        }
//    }
//
//    /**
//     * 查询已开通的产品列表
//     */
//    @GetMapping("/openProductList")
//    public R<Void> openProductList() {
//        String method = "express.channel.getlist";
//
//        String returnBody = getReturnBody("", method, apiOrder);
//        JSONObject jsonObject = JSONObject.parseObject(returnBody);
//        Boolean success = jsonObject.getBoolean("success");
//        if (success) {
//            List<EjfLogisticsProductInfo> productInfoList = new ArrayList<>();
//            JSONArray data = jsonObject.getJSONArray("data");
//            System.out.println(data);
//            for (Object datum : data) {
//                EjfLogisticsProductInfo productInfo = BeanUtil.toBean(datum, EjfLogisticsProductInfo.class);
//                productInfoList.add(productInfo);
//            }
//            productInfoMapper.insertOrUpdateBatch(productInfoList);
//        }
//        return success ? R.ok() : R.fail();
//    }
//
//
//    /**
//     * 查询交货仓库列表
//     * @param channelId 物流产品id
//     */
//    @GetMapping("/getHouseList")
//    public R<Object> getHouseList(String channelId) {
//
//        String method = "common.warehouse.getlist";
//        Map<String, Object> paramMap = new HashMap<>();
//        if (channelId != null) {
//            paramMap.put("channelId",channelId);
//        }
//        String string = JsonUtils.toJsonString(paramMap);
//        String returnBody = getReturnBody(string, method, apiOrder);
//        JSONObject jsonObject = JSONObject.parseObject(returnBody);
//        Boolean success = jsonObject.getBoolean("success");
//        JSONArray data = null;
//        if (success) {
//            data = jsonObject.getJSONArray("data");
//        }
//        return success ? R.ok(data) : R.fail();
//    }
//
//    /**
//     * 生成签名,返回url
//     * @return 签名
//     */
//    public String createUrl(String data, String method,String apiUrl) {
//        // 获取时间戳
//        Long timeCache = getTimeCache();
//        // 按顺序拼接
//        String sign = MD5Util.doMd5(apiToken + userId + data + format + method + timeCache + version + apiToken);
//        String lowerCase = sign.toLowerCase();
//        // MD5加密
//        return apiUrl + "?" + "user_id=" + userId + "&method=" + method + "&format=" + format + "&timestamp=" + timeCache + "&sign=" + lowerCase + "&version=" + version;
//    }
//
//    /**
//     * 从缓存中取出时间戳
//     */
//    public Long getTimeCache() {
//        Long timeStamp = RedisUtils.getCacheObject("EJFTimeStamp");
//        if (timeStamp == null) {
//            Long time = System.currentTimeMillis();
//            RedisUtils.setCacheObject("EJFTimeStamp",time, Duration.ofSeconds(300));
//            return time;
//        }
//        return timeStamp;
//    }
//
//    /**
//     * 发送请求获取返会数据
//     * @param data 请求数据json
//     * @param method 请求方法名
//     * @param apiUrl 请求路径
//     */
//    private String getReturnBody(String data, String method, String apiUrl) {
//
//        String url = createUrl(data, method, apiUrl);
//        HttpClient httpClient = HttpClients.createDefault();
//        HttpPost post = new HttpPost(testAddr + url);
//        post.setHeader("Content-Type", "application/json;charset=utf-8");
//        post.setHeader("Accept", "application/json");
//        post.setHeader("Content-Encoding", "gzip");
//        post.setEntity(new StringEntity(data,StandardCharsets.UTF_8));
//        HttpResponse httpResponse = null;
//        try {
//            httpResponse = httpClient.execute(post);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        HttpEntity response = httpResponse.getEntity();
//        try {
//            return EntityUtils.toString(response,StandardCharsets.UTF_8);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//    /**
//     * 测试访问
//     */
//    @GetMapping("/test")
//    public String testUrl() {
//        String method = "express.channel.getlist";
//        HttpClient httpClient = HttpClients.createDefault();
//        Map<String, Object> paramMap = new HashMap<>();
////        paramMap.put("waybillNumber","LW236181999CN");
////        paramMap.put("printRemark","0");
//        String data = JsonUtils.toJsonString(paramMap);
////        String data = "{\"waybillNumber\":\"LW236181999CN\",\"printRemark\":\"0\"}";
////        String data = "";
//        String url = createUrl(data, method, apiOrder);
//        HttpPost post = new HttpPost(testAddr + url);
//        post.setHeader("Content-Type", "application/json;charset=utf-8");
//        post.setHeader("Accept", "application/json");
//        post.setHeader("Content-Encoding", "gzip");
//        post.setEntity(new StringEntity(data,StandardCharsets.UTF_8));
//        HttpResponse httpResponse = null;
//        try {
//            httpResponse = httpClient.execute(post);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        int code = httpResponse.getStatusLine().getStatusCode();
//        HttpEntity response = httpResponse.getEntity();
//        try {
//            return code + EntityUtils.toString(response,StandardCharsets.UTF_8);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
//}
